package gin

import (
	"encoding/json"
	"net/http"
)

type Ctx struct {
	w http.ResponseWriter
	req *http.Request
	exe []HandlerFunc
	Header http.Header
	index int
	restful map[string]string
}

func newCtx(w http.ResponseWriter,req *http.Request) *Ctx {
	c := &Ctx{
		w: w,
		req: req,
		index: -1,
		restful: make(map[string]string),
	}
	c.Header = w.Header()
	c.req.ParseForm()
	return c
}

func (c *Ctx) Getw() http.ResponseWriter {
	return c.w
}

func (c *Ctx) GetReq() *http.Request {
	return c.req
}

func (c *Ctx) GetMethod() string {
	return c.req.Method
}

func (c *Ctx) GetUrl() string {
	return c.req.URL.Path
}

func (c *Ctx) SetStatus(code int) {
	c.w.WriteHeader(code)
}

func (c *Ctx) SetHeader(key string,value string)  {
	c.w.Header().Set(key,value)
}

func (c *Ctx) Write(data []byte) {
	c.w.Write(data)
}

func (c *Ctx) Json(code int,data interface{})  {
	c.SetStatus(code)
	bytes,err := json.Marshal(data)
	if err != nil {
		c.Error(http.StatusInternalServerError,err.Error())
	}
	c.Write(bytes)
}

func (c *Ctx) Text(code int,str string)  {
	c.SetStatus(code)
	c.Write([]byte(str))
}

func (c *Ctx) Error(code int,err string)  {
	c.Text(code,err)
}

func (c *Ctx) setRestful(key string,val string) {
	c.restful[key] = val
}

func (c *Ctx) GetRestfaul(key string) string {
	return c.restful[key]
}


func (c *Ctx) Form(key string) string {
	return c.req.Form.Get(key)
}

func (c *Ctx) Get(key string) string {
	return c.req.URL.Query().Get(key)
}

func (c *Ctx) addMid(f... HandlerFunc) {
	c.exe = append(c.exe, f...)
}

// 这一段Next写的还是很巧妙的---相比较于koa的实现
func (c *Ctx) Next() {
	c.index++
	for ;c.index<len(c.exe);c.index++ {
		c.exe[c.index](c)
	}
}

//func (c *Ctx) FileDownload()  {
//
//}
